package com.gdk.ksoft.assembly.dialog;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.gdk.ksoft.R;
import com.gdk.ksoft.data.common.SystemData;
import com.gdk.ksoft.ui.MainActivity;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lidroid.xutils.view.annotation.event.OnItemClick;
import com.zkc.helper.printer.Device;
import com.zkc.helper.printer.PrinterClass;
import com.zkc.helper.printer.PrinterClassFactory;
import com.zkc.helper.printer.bt.BtService;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by hel on 2014-12-05.
 * 蓝牙打印对话框
 */
public class BluetoothPrinterDialog extends Dialog {

    public interface OnBluetoothConnectedListener{
        public void onBluetoothConnected(boolean isSuccessful);
    }

    public static final String TAG = BluetoothPrinterDialog.class.getSimpleName();
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;

    @ViewInject(R.id.dialog_bluetooth_printer_imgScanner)private ImageView imgScanner;//搜索附近蓝牙
    @ViewInject(R.id.dialog_bluetooth_printer_lstbluetooth)private ListView lstBluetooth;//蓝牙列表
    @ViewInject(R.id.dialog_bluetooth_printer_txtTitle)private TextView txtTitle;//标题蓝文字
    private BluetoothAdapter bluetoothAdapter;//蓝牙数据适配器
    private OnBluetoothConnectedListener listener;

    private Handler mhandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MESSAGE_STATE_CHANGE:// 蓝牙连接状
                    switch (msg.arg1) {
                        case PrinterClass.STATE_CONNECTED:// 已经连接
                            break;
                        case PrinterClass.STATE_CONNECTING:// 正在连接
                            break;
                        case PrinterClass.STATE_LISTEN:
                        case PrinterClass.STATE_NONE:
                            System.out.println("----->蓝牙无链接");
                            break;
                        case PrinterClass.SUCCESS_CONNECT:
                            break;
                        case PrinterClass.FAILED_CONNECT:
                            System.out.println("----->蓝牙链接失败");
                            break;
                        case PrinterClass.LOSE_CONNECT:
                            System.out.println("----->蓝牙失去链接");
                            Log.i(TAG, "LOSE_CONNECT");
                    }
                    break;
                case MESSAGE_READ:
                    // sendFlag = false;//缓冲区已准备
                    break;
                case MESSAGE_WRITE:// 缓冲区未初始化
                    // sendFlag = true;
                    break;
            }
        }
    };

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    break;
                case 1:// 扫描完毕
                    //PrintActivity.pl.stopScan();
                    Device d=(Device)msg.obj;
                    if(d!=null)
                    {
                        if(MainActivity.deviceList==null)
                        {
                            MainActivity.deviceList=new ArrayList<Device>();
                        }

                        if(!checkData(MainActivity.deviceList,d))
                        {
                            MainActivity.deviceList.add(d);
                            bluetoothAdapter.notifyDataSetChanged();
                        }
                    }
                    break;
                case 2:// 停止扫描
                    break;
            }
        }
    };

    private Thread checkThread = new Thread() {
        public void run() {
            while (true) {
                if(MainActivity.checkState)
                {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    txtTitle.post(new Runnable() {
                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            if (MainActivity.pl != null) {
                                if (MainActivity.pl.getState() == PrinterClass.STATE_CONNECTED) {
                                    txtTitle.setText("蓝牙打印机(连接成功)");
                                } else if (MainActivity.pl.getState() == PrinterClass.STATE_CONNECTING) {
                                    txtTitle.setText("蓝牙打印机(正在连接)");
                                } else if(MainActivity.pl.getState() == PrinterClass.LOSE_CONNECT
                                        ||MainActivity.pl.getState() == PrinterClass.FAILED_CONNECT){
                                    MainActivity.checkState=false;
                                    txtTitle.setText("蓝牙打印机(连接失败)");
                                }else{
                                    txtTitle.setText("蓝牙打印机(等待连接)");
                                }
                            }
                        }
                    });
                }
            }
        }
    };

    /**
     * 设备检测
     * @param list
     * @param d
     * @return
     */
    private boolean checkData(List<Device> list,Device d)
    {
        for (Device device : list) {
            if(device.deviceAddress.equals(d.deviceAddress))
            {
                return true;
            }
        }
        return false;
    }

    public BluetoothPrinterDialog(Context context,OnBluetoothConnectedListener listener){
        super(context);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        View rootView = View.inflate(context, R.layout.dialog_bluetooth_printer,null);
        ViewUtils.inject(this, rootView);
        setContentView(rootView);
        this.listener = listener;
        if(MainActivity.pl == null)
            MainActivity.pl = (BtService)PrinterClassFactory.create(0,context,mhandler,handler);
        MainActivity.checkState=true;
        bluetoothAdapter = new BluetoothAdapter(context,MainActivity.deviceList);
        lstBluetooth.setAdapter(bluetoothAdapter);
        checkThread.start();//启动检测线程
    }

    @OnClick(value={R.id.dialog_bluetooth_printer_imgScanner,R.id.dialog_bluetooth_printer_txtCancel,
            R.id.dialog_bluetooth_printer_txtOk})
    public void onViewClick(View view){
        switch(view.getId()){
            case R.id.dialog_bluetooth_printer_imgScanner://扫描
                scanBluetoothDevices();//搜索蓝牙设备
                break;
            case R.id.dialog_bluetooth_printer_txtCancel://取消
                if(listener!=null) listener.onBluetoothConnected(false);
                this.dismiss();
                break;
            case R.id.dialog_bluetooth_printer_txtOk://完成
                if(MainActivity.pl == null||MainActivity.pl.getState()!=PrinterClass.STATE_CONNECTED){
                    Toast.makeText(getContext(),"蓝牙打印机未连接!",Toast.LENGTH_SHORT).show();
                    return;
                }
                this.dismiss();
                if(listener!=null) listener.onBluetoothConnected(true);
                break;
        }
    }

    /**
     * 搜搜蓝牙设备
     */
    public void scanBluetoothDevices(){
        if(MainActivity.deviceList!=null){
            MainActivity.deviceList.clear();
            bluetoothAdapter.notifyDataSetChanged();
        }
        if(!MainActivity.pl.IsOpen())
            MainActivity.pl.open(getContext());
        MainActivity.pl.scan();
        MainActivity.deviceList.addAll(MainActivity.pl.getDeviceList());
        bluetoothAdapter.notifyDataSetChanged();
    }

    /**
     * 当List的项被选中时触发
     */
    @OnItemClick(value = {R.id.dialog_bluetooth_printer_lstbluetooth})
    protected void onListItemClick(AdapterView<?> av, View v, int position, long id) {
        final Device device = (Device)av.getItemAtPosition(position);
        SystemData.printerDeviceAddress = device.deviceAddress;//获取打印机的MAC地址
        MainActivity.pl.connect(device.deviceAddress);//连接到设备
    }

    @Override
    protected void onStart() {
        MainActivity.checkState = true;
        super.onStart();
    }

    /**
     * 蓝牙数据适配器
     */
    public class BluetoothAdapter extends BaseAdapter{

        private Context context;
        private List<Device> lst;

        public BluetoothAdapter(Context context,List<Device> lst) {
            super();
            this.context = context;
            this.lst = lst;
        }

        @Override
        public int getCount() {
            return lst == null?0:lst.size();
        }

        @Override
        public Object getItem(int position) {
            return lst.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final Device device = lst.get(position);
            View rootView = View.inflate(context,android.R.layout.simple_list_item_1,null);
            TextView txtText = (TextView)rootView.findViewById(android.R.id.text1);
            txtText.setText("【"+device.deviceName+"】"+device.deviceAddress);
            return rootView;
        }
    }
}
